package com.study.service.impl;


import com.study.account.BalanceInfo;
import com.study.dao.EcommerceBalanceDao;
import com.study.entity.EcommerceBalance;
import com.study.filter.AccessContext;
import com.study.service.IBalanceService;
import com.study.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BalanceServiceImpl implements IBalanceService {

    @Autowired
    private EcommerceBalanceDao ecommerceBalanceDao;

    /**
     * 当前用户余额信息
     * @return
     */
    @Override
    public BalanceInfo getCurrentUserBalanceInfo() {

        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();

        BalanceInfo balanceInfo = new BalanceInfo(
                loginUserInfo.getId(), new BigDecimal("0.00")
        );

        EcommerceBalance ecommerceBalance = ecommerceBalanceDao.findByUserId(loginUserInfo.getId());

        if (null != ecommerceBalance) {
            balanceInfo.setBalance(ecommerceBalance.getBalance());
        } else {
            //如果还没有用户余额记录、创建出来、余额设置为0.00
            EcommerceBalance newBalance = new EcommerceBalance();
            newBalance.setUserId(loginUserInfo.getId());
            newBalance.setBalance(new BigDecimal("0.00"));
            ecommerceBalanceDao.save(newBalance);
        }
        return balanceInfo;
    }

    /**
     * 扣减用户余额
     * @param balanceInfo
     * @return
     */
    @Override
    public BalanceInfo deductBalance(BalanceInfo balanceInfo) {

        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();

        EcommerceBalance ecommerceBalance = ecommerceBalanceDao.findByUserId(loginUserInfo.getId());

        if(null == ecommerceBalance
                || (ecommerceBalance.getBalance()
                .subtract(balanceInfo.getBalance())).compareTo(BigDecimal.ZERO) == -1){

            throw new RuntimeException("用户余额不足！");

        }

        //扣减之前余额
        BigDecimal balanceBalance = ecommerceBalance.getBalance();

        ecommerceBalance.setBalance(ecommerceBalance.getBalance()
                .subtract(balanceInfo.getBalance()));

        log.info("用户id: [{}] 、扣减之前余额:[{}]、扣减之后余额：[{}]",
                ecommerceBalanceDao.save(ecommerceBalance).getId()
                ,balanceBalance
                ,ecommerceBalance.getBalance());

        return new BalanceInfo(
                ecommerceBalance.getUserId(),
                ecommerceBalance.getBalance()
        );
    }
}
